package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import com.mongodb.client.result.DeleteResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Integer userId, ApArticleSearchDto dto) {
//        根据关键字查询历史搜索记录是否存在
        Query query = new Query();
//          -设置查询条件
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("keyword").is(dto.getSearchWords()));
        long count = mongoTemplate.count(query, ApUserSearch.class);
//        如果为空则进行保存
        if (count == 0 ){
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(userId);
            apUserSearch.setEquipmentId(dto.getEquipmentId());
            apUserSearch.setKeyword(dto.getSearchWords());
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }else {
//        如果不为空则进行更新
            Update update = new Update();
            update.set("createdTime",new Date());
            mongoTemplate.updateFirst(query,update,ApUserSearch.class);
        }

    }

    /**
     * 加载用户搜索记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        User user = UserThreadLocalUtil.get();
//        构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));
//        设置分页信息，只查前5条
        query.with(PageRequest.of(0,5));
//        设置排序
        query.with(Sort.by("createdTime"));
//        执行分页查询
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除用户搜索记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        //1.构建删除条件
        Query query = new Query();
        //1.1 批量删除传入多个搜索记录集合
        List<ApUserSearch> hisList = dto.getHisList();
        if (!CollectionUtils.isEmpty(hisList)) {
            List<String> collect = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
            query.addCriteria(Criteria.where("id").in(collect));
            //2.执行删除文档数据
            mongoTemplate.remove(query, ApUserSearch.class);
        }
        return ResponseResult.okResult();
    }
}
